package cn.exrick.manager.service.hotclassload;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

public class MyClassLoader extends ClassLoader {

    private String classPath;

    public MyClassLoader() {
        super(ClassLoader.getSystemClassLoader());
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource("");
        String path = url.getPath();
        this.classPath = path.substring(1,path.length());
    }

    @Override
    public Class<?> findClass(String className) {
        byte[] data = loadClassData(className);
        return this.defineClass(className, data, 0, data.length);
    }

    private byte[] loadClassData(String className) {
        className = className.replace(".", "//");
        try (InputStream inputStream = new FileInputStream(new File(classPath + className + ".class")); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            int b = 0;
            while ((b = inputStream.read()) != -1) {
                bos.write(b);
            }
            return bos.toByteArray();
        } catch (Exception se) {
            return null;
        }
    }
}
